<template>
  <div class="sales-trend-chart">
    <div class="sales-trend-chart__header">
      <div class="sales-trend-chart__title">
        <h3>销售趋势</h3>
        <p>{{ rangeDescription }}</p>
      </div>
      <div class="sales-trend-chart__range-selector">
        <button 
          v-for="range in timeRanges" 
          :key="range.value" 
          :class="['range-button', { active: selectedRange === range.value }]"
          @click="changeRange(range.value)"
        >
          {{ range.label }}
        </button>
      </div>
    </div>
    
    <div class="sales-trend-chart__summary">
      <div class="summary-item">
        <span class="summary-item__label">总销售额</span>
        <span class="summary-item__value">{{ totalSales.toLocaleString('zh-CN') }} USDT</span>
        <span class="summary-item__trend" :class="{ 'positive': salesGrowth > 0, 'negative': salesGrowth < 0 }">
          <i class="fas" :class="salesGrowth > 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
          {{ Math.abs(salesGrowth) }}%
        </span>
      </div>
      <div class="summary-item">
        <span class="summary-item__label">总订单量</span>
        <span class="summary-item__value">{{ totalOrders.toLocaleString('zh-CN') }}</span>
        <span class="summary-item__trend" :class="{ 'positive': ordersGrowth > 0, 'negative': ordersGrowth < 0 }">
          <i class="fas" :class="ordersGrowth > 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
          {{ Math.abs(ordersGrowth) }}%
        </span>
      </div>
      <div class="summary-item">
        <span class="summary-item__label">总佣金</span>
        <span class="summary-item__value">{{ totalCommission.toLocaleString('zh-CN') }} USDT</span>
        <span class="summary-item__trend" :class="{ 'positive': commissionGrowth > 0, 'negative': commissionGrowth < 0 }">
          <i class="fas" :class="commissionGrowth > 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
          {{ Math.abs(commissionGrowth) }}%
        </span>
      </div>
    </div>
    
    <div class="sales-trend-chart__chart">
      <apexchart
        height="360"
        type="area"
        :options="chartOptions"
        :series="series"
      ></apexchart>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue'
import { generateSalesTrendData } from '@/utils/mockData'

// 定义时间范围选项
const timeRanges = [
  { label: '7天', value: 7 },
  { label: '30天', value: 30 },
  { label: '90天', value: 90 }
]

// 当前选择的时间范围
const selectedRange = ref(timeRanges[1].value)

// 获取销售趋势数据
const trendData = ref(generateSalesTrendData(selectedRange.value))

// 监听时间范围变化，更新数据
watch(selectedRange, (newValue) => {
  trendData.value = generateSalesTrendData(newValue)
})

// 计算时间范围描述
const rangeDescription = computed(() => {
  const today = new Date()
  const startDate = new Date(today)
  startDate.setDate(today.getDate() - selectedRange.value)
  
  const formatDate = (date: Date) => {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }
  
  return `${formatDate(startDate)} 至 ${formatDate(today)}`
})

// 计算总销售额
const totalSales = computed(() => {
  return Math.round(trendData.value.reduce((sum, item) => sum + item.sales, 0))
})

// 计算总订单量
const totalOrders = computed(() => {
  return trendData.value.reduce((sum, item) => sum + item.orders, 0)
})

// 计算总佣金
const totalCommission = computed(() => {
  return Math.round(trendData.value.reduce((sum, item) => sum + item.commission, 0))
})

// 销售额增长率（模拟数据）
const salesGrowth = ref(Math.round((Math.random() * 40) - 10))
const ordersGrowth = ref(Math.round((Math.random() * 30) - 5))
const commissionGrowth = ref(Math.round((Math.random() * 50) - 10))

// 图表系列数据
const series = computed(() => {
  return [
    {
      name: '销售额',
      data: trendData.value.map(item => parseFloat(item.sales.toFixed(2)))
    },
    {
      name: '订单量',
      data: trendData.value.map(item => item.orders)
    }
  ]
})

// 图表X轴日期
const categories = computed(() => {
  return trendData.value.map(item => item.date)
})

// 图表配置选项
const chartOptions = computed(() => {
  return {
    chart: {
      type: 'area',
      height: 350,
      fontFamily: 'DM Sans, sans-serif',
      toolbar: {
        show: false
      },
      zoom: {
        enabled: false
      }
    },
    colors: ['#FF4757', '#00E396'],
    dataLabels: {
      enabled: false
    },
    stroke: {
      curve: 'smooth',
      width: [3, 3]
    },
    fill: {
      type: 'gradient',
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.7,
        opacityTo: 0.2,
        stops: [0, 90, 100]
      }
    },
    markers: {
      size: 4,
      strokeWidth: 0,
      hover: {
        size: 6
      }
    },
    grid: {
      borderColor: '#e0e0e0',
      row: {
        colors: ['transparent', 'transparent'],
        opacity: 0.2
      }
    },
    xaxis: {
      categories: categories.value,
      labels: {
        style: {
          fontSize: '12px',
          fontFamily: 'DM Sans, sans-serif'
        },
        formatter: function(value: string) {
          // 简化日期显示，只展示月/日
          const date = new Date(value)
          return `${date.getMonth() + 1}/${date.getDate()}`
        }
      },
      axisBorder: {
        show: false
      },
      axisTicks: {
        show: false
      }
    },
    yaxis: [
      {
        title: {
          text: '销售额 (USDT)',
          style: {
            fontSize: '12px',
            fontWeight: 500
          }
        },
        labels: {
          formatter: function(value: number) {
            return value.toFixed(0)
          }
        }
      },
      {
        opposite: true,
        title: {
          text: '订单量',
          style: {
            fontSize: '12px',
            fontWeight: 500
          }
        },
        labels: {
          formatter: function(value: number) {
            return value.toFixed(0)
          }
        }
      }
    ],
    tooltip: {
      shared: true,
      intersect: false,
      y: {
        formatter: function(value: number, { seriesIndex }: { seriesIndex: number }) {
          if (seriesIndex === 0) {
            return `${value.toFixed(2)} USDT`
          }
          return value
        }
      }
    },
    legend: {
      position: 'top',
      horizontalAlign: 'right',
      floating: true,
      offsetY: -25,
      offsetX: -5,
      markers: {
        width: 10,
        height: 10,
        radius: 6
      }
    }
  }
})

// 切换时间范围
const changeRange = (range: number) => {
  selectedRange.value = range
}

// 组件挂载后初始化
onMounted(() => {
  // 可以在这里添加额外的初始化逻辑
})

// 组件卸载前清理数据
onBeforeUnmount(() => {
  trendData.value = [];
})
</script>

<style scoped lang="scss">
.sales-trend-chart {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 24px;
  
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  &__title {
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #2F3542;
      margin: 0 0 4px 0;
    }
    
    p {
      font-size: 13px;
      color: #6C757D;
      margin: 0;
    }
  }
  
  &__range-selector {
    display: flex;
    gap: 8px;
    
    .range-button {
      background: none;
      border: 1px solid #E0E0E0;
      border-radius: 20px;
      padding: 6px 12px;
      font-size: 13px;
      color: #6C757D;
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:hover {
        background-color: #F8F9FA;
      }
      
      &.active {
        background-color: #FF4757;
        border-color: #FF4757;
        color: white;
      }
    }
  }
  
  &__summary {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
    flex-wrap: wrap;
    
    .summary-item {
      display: flex;
      flex-direction: column;
      flex: 1;
      min-width: 120px;
      
      &__label {
        font-size: 14px;
        color: #6C757D;
        margin-bottom: 4px;
      }
      
      &__value {
        font-size: 24px;
        font-weight: 700;
        color: #2F3542;
        margin-bottom: 4px;
      }
      
      &__trend {
        display: inline-flex;
        align-items: center;
        font-size: 13px;
        font-weight: 500;
        
        i {
          margin-right: 4px;
          font-size: 10px;
        }
        
        &.positive {
          color: #28A745;
        }
        
        &.negative {
          color: #DC3545;
        }
      }
    }
  }
  
  &__chart {
    position: relative;
    
    .apexcharts-tooltip {
      background: #fff;
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
      border: none;
      border-radius: 8px;
      padding: 12px;
    }
  }
}

@media (max-width: 768px) {
  .sales-trend-chart {
    padding: 16px;
    
    &__header {
      flex-direction: column;
      align-items: flex-start;
      
      .sales-trend-chart__title {
        margin-bottom: 12px;
      }
    }
    
    &__summary {
      flex-direction: column;
      gap: 16px;
      
      .summary-item {
        min-width: auto;
      }
    }
  }
}
</style>